<template>
    <div id="login-modal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-login" role="document">
            <div class="modal-content">

                <div class="modal-body" :showStatus="showDialog">
                    <!--登录-->
                    <div class="login-div" v-show="MODAL_STATUS===STATUS_LOGIN">
                        <div class="loginHeader">
                            <h3>会&nbsp;&nbsp;员&nbsp;&nbsp;登&nbsp;&nbsp;录</h3>
                            <button type="button" class="dialogClose close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        </div>
                        <div class="form-content">
                            <div class="form-group">
                                <input v-model="member.mobile" class="form-control" placeholder="手机号">
                            </div>
                            <div class="form-group">
                                <input v-model="member.password" class="form-control" type="password"  placeholder="密码">
                            </div>
                            <div class="form-group">
                                <div class="input-group">
                                    <input id="image-code-input" class="loginInput " type="text" placeholder="验证码"
                                           v-model="member.imgCode">
                                    <div class="input-group-addon" id="image-code-addon">
                                        <img id="image-code" alt="验证码" v-on:click="loadImageCode()" />
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <button v-on:click="clientLogin()" class="clickButtom btn btn-primary btn-block submit-button">
                                    登&nbsp;&nbsp;录
                                </button>
                            </div>

                            <div class="form-group">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" class="checkBoxRemember rememberme" v-model="rememberme">记住密码
                                    </label>
                                    <div class="pull-right">
                                        <!--跳转忘记密码页面-->
                                        <a href="javascript:;" v-on:click="toForgetPWD()">忘记密码</a>&nbsp;
                                        <!--跳转注册页面-->
                                        <a href="javascript:;" v-on:click="toRegisterMEM()">我要注册</a>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group to-register-MEM"></div>
                        </div>

                    </div>
                    <!--登录end-->
                    <!--注册-->
                    <div class="register-MEM" v-show="MODAL_STATUS===STATUS_REGISTER">
                        <div class="loginHeader">
                            <h3>免&nbsp;&nbsp;费&nbsp;&nbsp;注&nbsp;&nbsp;册&nbsp;&nbsp;会&nbsp;&nbsp;员</h3>
                            <button type="button" class="dialogClose close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        </div>
                        <!--手机号及验证码-->
                        <div class="form-content">
                            <div class="form-group">
                                <input v-on:blur="onRegisterMobileBlur()"
                                       v-bind:class="registerMobileValidatorClass"
                                       id="register-mobile"
                                       v-model="memberRegister.mobile"
                                       class="form-control" placeholder="手机号">
                                <span v-show="registerMobileValidator===false" class="text-danger">请输入正确的手机号码</span>
                            </div>
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="validateSendCode">
                                        <input v-on:blur="onRegisterMobileCodeBlur()"
                                               v-bind:class="registerMobileCodeValidatorClass"
                                               id="register-mobile-code"
                                               v-model="memberRegister.shortMessageCode"
                                               class="validateCode form-control" placeholder="手机验证码">
                                        <button class="btn btn-outline-secondary"
                                                id="register-send-code-btn"
                                                v-on:click="sendMobileSMSCodeForRegister()"
                                        >发送验证码
                                        </button>
                                    </div>
                                </div>
                                <span v-show="registerMobileCodeValidator===false" class="text-danger">请输入短信6位验证码</span>
                            </div>
                            <!--昵称-->
                            <div class="form-group">
                                <input v-on:blur="onRegisterNameBlur()"
                                       v-bind:class="registerNameValidatorClass"
                                       id="register-name"
                                       v-model="memberRegister.nickName"
                                       class="form-control" placeholder="昵称">
                                <span v-show="registerNameValidator===false"
                                      class="text-danger">昵称请输入2-20位中文、字母、数字、下划线组合</span>
                            </div>
                            <!--密码-->
                            <div class="form-group">
                                <input v-on:blur="onRegisterPasswordBlur()"
                                       v-bind:class="registerPasswordValidatorClass"
                                       id="register-password"
                                       v-model="memberRegister.passwordOriginal"
                                       class="form-control" placeholder="密码" type="password">
                                <span v-show="registerPasswordValidator===false"
                                      class="text-danger">密码最少6位，包含至少1字母和1个数字</span>
                            </div>
                            <div class="form-group">
                                <input v-on:blur="onRegisterPasswordConfirmBlur()"
                                       v-bind:class="registerPasswordConfirmValidatorClass"
                                       id="register-confirm-password"
                                       v-model="memberRegister.passwordConfirm"
                                       class="form-control" placeholder="确认密码" type="password"
                                       name="memberRegisterPasswordConfirm">
                                <span v-show="registerPasswordConfirmValidator===false" class="text-danger">确认密码和密码一致</span>
                            </div>
                            <!--注册-->
                            <div class="form-group">
                                <button class="clickButtom btn btn-primary btn-block submit-button" v-on:click="register()">
                                    注&nbsp;&nbsp;册
                                </button>
                            </div>
                            <!--登录modal_status跳转-->
                            <div class="form-group to-login-acount">
                                <a href="javascript:;" v-on:click="toLoginAcount()">我要登录</a>
                            </div>
                        </div>

                    </div>
                    <!--注册end-->
                    <!--忘记密码-->
                    <div class="forget-PWD" v-show="MODAL_STATUS===STATUS_FORGET">
                        <div class="loginHeader">
                            <h3>重&nbsp;&nbsp;置&nbsp;&nbsp;密&nbsp;&nbsp;码</h3>
                            <button type="button" class="dialogClose close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        </div>
                        <div class="form-content">
                            <div class="form-group">
                                <input v-on:blur="onForgetMobileBlur()"
                                       v-bind:class="forgetMobileValidatorClass"
                                       id="forget-mobile"
                                       v-model="memberForget.mobile"
                                       class="form-control" placeholder="手机号">
                                <span v-show="forgetMobileValidator===false" class="text-danger">手机号11位数字，且必须已注册</span>
                            </div>
                            <div class="form-group">
                                <div class="input-group">

                                    <div class="input-group-append">
                                        <input v-on:blur="onForgetMobileCodeBlur()"
                                               v-bind:class="forgetMobileCodeValidatorClass"
                                               id="forget-mobile-code"
                                               v-model="memberForget.shortMessageCode"
                                               class="validateCode form-control" placeholder="手机验证码">
                                        <button class="btn btn-outline-secondary"
                                                id="forget-send-code-btn"
                                                v-on:click="sendMobileSMSCodeForForget()"
                                        >发送验证码
                                        </button>
                                    </div>
                                </div>
                                <span v-show="forgetMobileCodeValidator===false" class="text-danger">请输入短信6位验证码</span>
                            </div>
                            <!--忘记密码-->
                            <div class="form-group">
                                <input v-on:blur="onForgetPasswordBlur()"
                                       v-bind:class="forgetPasswordValidatorClass"
                                       id="forget-password"
                                       v-model="memberForget.passwordOriginal"
                                       class="form-control" placeholder="密码" type="password">
                                <span v-show="forgetPasswordValidator===false"
                                      class="text-danger">密码最少6位，包含至少1字母和1个数字</span>
                            </div>
                            <div class="form-group">
                                <input v-on:blur="onForgetPasswordConfirmBlur()"
                                       v-bind:class="forgetPasswordConfirmValidatorClass"
                                       id="forget-confirm-password"
                                       v-model="memberForget.passwordConfirm"
                                       class="form-control" placeholder="确认密码" type="password"
                                       name="memberRegisterPasswordConfirm">
                                <span v-show="forgetPasswordConfirmValidator===false" class="text-danger">确认密码和密码一致</span>
                            </div>
                            <div class="form-group">
                                <button v-on:click="resetPWD()" class="clickButtom btn btn-primary btn-block submit-button">
                                    重&nbsp;&nbsp;置
                                </button>
                            </div>
                            <!--登录modal_status跳转-->
                            <div class="form-group to-login-acount">
                                <a href="javascript:;" v-on:click="toLoginAcount()">我要登录</a>
                            </div>
                        </div>

                    </div>
                    <!--忘记密码-end-->
                </div>
                <!--modal-body-end-->
            </div>
            <!--modal-content-end-->
        </div>
    </div>
</template>

<script>
    export default {
        name: "main-login",
        props:{
            showDialog:{
                default:"STATUS_REGISTER"
            }
        },
        data: function () {
            return {
                // 模态框内容切换：登录、注册、忘记密码
                STATUS_LOGIN: "STATUS_LOGIN",
                STATUS_REGISTER: "STATUS_REGISTER",
                STATUS_FORGET: "STATUS_FORGET",
                MODAL_STATUS: "",//跳转页面的v-show
                //本地memberLogin登录变量：返回后端member
                member: {
                    mobile:"",
                    password:"",
                    imgCode:""},
                //本地注册变量，返回后端member
                memberRegister: {},
                //本地忘记密码变量，返回后端member
                memberForget: {},
                rememberme: true, //记住密码
                imageCodeToken: "",
                // 注册框显示错误信息
                registerMobileValidator: null,
                registerMobileCodeValidator: null,
                registerNameValidator: null,
                registerPasswordValidator: null,
                registerPasswordConfirmValidator: null,

                // 忘记密码框显示错误信息
                forgetMobileValidator: null,
                forgetMobileCodeValidator: null,
                forgetPasswordValidator: null,
                forgetPasswordConfirmValidator: null,
            }
        },
        computed: {
            registerMobileValidatorClass: function () {
                return {
                    'border-success': this.registerMobileValidator === true,
                    'border-danger': this.registerMobileValidator === false,
                }
            },
            registerMobileCodeValidatorClass: function () {
                return {
                    'border-success': this.registerMobileCodeValidator === true,
                    'border-danger': this.registerMobileCodeValidator === false,
                }
            },
            registerNameValidatorClass: function () {
                return {
                    'border-success': this.registerNameValidator === true,
                    'border-danger': this.registerNameValidator === false,
                }
            },
            registerPasswordValidatorClass: function () {
                return {
                    'border-success': this.registerPasswordValidator === true,
                    'border-danger': this.registerPasswordValidator === false,
                }
            },
            registerPasswordConfirmValidatorClass: function () {
                return {
                    'border-success': this.registerPasswordConfirmValidator === true,
                    'border-danger': this.registerPasswordConfirmValidator === false,
                }
            },
            forgetMobileValidatorClass: function () {
                return {
                    'border-success': this.forgetMobileValidator === true,
                    'border-danger': this.forgetMobileValidator === false,
                }
            },
            forgetMobileCodeValidatorClass: function () {
                return {
                    'border-success': this.forgetMobileCodeValidator === true,
                    'border-danger': this.forgetMobileCodeValidator === false,
                }
            },
            forgetPasswordValidatorClass: function () {
                return {
                    'border-success': this.forgetPasswordValidator === true,
                    'border-danger': this.forgetPasswordValidator === false,
                }
            },
            forgetPasswordConfirmValidatorClass: function () {
                return {
                    'border-success': this.forgetPasswordConfirmValidator === true,
                    'border-danger': this.forgetPasswordConfirmValidator === false,
                }
            },
        },
        mounted() {
            let _this = this;
            //**页面初始化设置的登录模态框
            _this.toLoginAcount();
            //监听全局总线，必须声明回调
            _this.$event.$on("openLoginModal",function () {
                _this.openLoginModal("STATUS_LOGIN");
            });
        },
        methods: {
            openLoginModal(showDialog) {
                let _this = this;
                //放入toLoginAcount,这里实现，3个模态框切换，验证码不会刷新
                //_this.loadImageCode();
                if(showDialog==="STATUS_LOGIN"){
                    //登录之前刷新验证码
                    this.loadImageCode();
                    this.MODAL_STATUS="STATUS_LOGIN";
                }else if(showDialog==="STATUS_REGISTER"){
                    this.MODAL_STATUS="STATUS_REGISTER";
                }else if(showDialog==="STATUS_FORGET"){
                    this.MODAL_STATUS="STATUS_FORGET";
                }
                //关闭模态框点击空白处自动关闭
                $("#login-modal").modal({
                    show:true,
                    backdrop:'static',
                    keyboard:false
                });
            },
            /*------------登录框/注册框/忘记密码框切换--------------*/
            toLoginAcount() {
                let _this = this;
                //从缓存中获取记住的手机号和密码，没有获取到=没有勾选记住我
                let rememberMember = LocalStorage.get(MEMBER_LOGIN_LOCAL);
                if (rememberMember) {
                    _this.member = rememberMember;
                }
                //显示登录框，刷新验证码
                _this.loadImageCode();
                _this.MODAL_STATUS = _this.STATUS_LOGIN;
            },

            toRegisterMEM() {
                let _this = this;
                _this.MODAL_STATUS = _this.STATUS_REGISTER;
            },
            toForgetPWD() {
                let _this = this;
                _this.MODAL_STATUS = _this.STATUS_FORGET;
            },

            //-------------------------------- 注册框校验 ----------------------------//

            onRegisterMobileBlur() {
                let _this = this;
                _this.registerMobileValidator = Pattern.validateMobile(_this.memberRegister.mobile);
                return _this.registerMobileValidator;
            },

            onRegisterMobileCodeBlur() {
                let _this = this;
                _this.registerMobileCodeValidator = Pattern.validateMobileCode(_this.memberRegister.shortMessageCode);
                return _this.registerMobileValidator;
            },

            onRegisterNameBlur() {
                let _this = this;
                _this.registerNameValidator = Pattern.validateName(_this.memberRegister.nickName);
                return _this.registerMobileValidator;
            },

            onRegisterPasswordBlur() {
                let _this = this;
                _this.registerPasswordValidator = Pattern.validatePasswordWeak(_this.memberRegister.passwordOriginal);
                return _this.registerMobileValidator;
            },

            onRegisterPasswordConfirmBlur() {
                let _this = this;
                let confirmPassword = $("#register-confirm-password").val();
                if (Tool.isEmpty(confirmPassword)) {
                    return _this.registerPasswordConfirmValidator = false;
                }
                return _this.registerPasswordConfirmValidator = (confirmPassword === _this.memberRegister.passwordOriginal);
            },

            //-------------------------------- 忘记密码框校验 ----------------------------//

            onForgetMobileBlur() {
                let _this = this;
                return _this.forgetMobileValidator = Pattern.validateMobile(_this.memberForget.mobile);
            },

            onForgetMobileCodeBlur() {
                let _this = this;
                return _this.forgetMobileCodeValidator = Pattern.validateMobileCode(_this.memberForget.shortMessageCode);
            },

            onForgetPasswordBlur() {
                let _this = this;
                return _this.forgetPasswordValidator = Pattern.validatePasswordWeak(_this.memberForget.passwordOriginal);
            },

            onForgetPasswordConfirmBlur() {
                let _this = this;
                let forgetPassword = $("#forget-confirm-password").val();
                if (Tool.isEmpty(forgetPassword)) {
                    return _this.forgetPasswordConfirmValidator = false;
                }
                return _this.forgetPasswordConfirmValidator = (forgetPassword === _this.memberForget.passwordOriginal);
            },

            //********************************自定义方法******************************//

            /**
             * 1.注册
             */
            register() {
                let _this = this;

                //[单注册校验]注册之前增加校验，一个文本框为false，都不提交return
                // let validatorRules=_this.onRegisterMobileBlur()
                // && _this.onRegisterMobileCodeBlur()
                // && _this.onRegisterNameBlur()
                // && _this.onRegisterPasswordBlur()
                // && _this.onRegisterPasswordConfirmBlur();

                //文本框全部校验
                let validatorRules1=_this.onRegisterMobileBlur();
                let validatorRules2=_this.onRegisterMobileCodeBlur();
                let validatorRules3=_this.onRegisterNameBlur();
                let validatorRules4=_this.onRegisterPasswordBlur();
                let validatorRules5=_this.onRegisterPasswordConfirmBlur();
                let validatorRules=validatorRules1 && validatorRules2 && validatorRules3 && validatorRules4 && validatorRules5;
                if(!validatorRules){
                    return;
                }
                //注册为密码加密
                _this.memberRegister.password = hex_md5(_this.memberRegister.passwordOriginal + KEY);

                //调用服务端注册接口
                _this.$axios.post(process.env.VUE_APP_SERVER + '/business/client/member/register',
                    _this.memberRegister)
                    .then((responseRegister) => {
                        let response = responseRegister.data;
                        if (response.success) {
                            toast.success("注册成功");
                            this.toLoginAcount();
                        } else {
                            toast.warning("注册失败："+response.responseMsg);
                        }
                    });
            },
            /**
             * 加载验证码
             */
            loadImageCode() {
                let _this=this;
                _this.imageCodeToken=Tool.get8UUID(8);
                $('#image-code').attr('src',process.env.VUE_APP_SERVER + '/business/client/kaptcha/image-code/'+_this.imageCodeToken);
            },
            /**
             * 登录
             */
            clientLogin() {
                let _this=this;
                //如果密码时缓存中取出，则不需要二次加密
                let c_md5=hex_md5(_this.member.password);
                //先判断是否与本地缓存相同
                let rememberMe=LocalStorage.get(MEMBER_LOGIN_LOCAL) || {};
                if(c_md5!==rememberMe.new_md5){
                    _this.member.password=hex_md5(_this.member.password+KEY);
                }
                _this.member.imgCodeToken=_this.imageCodeToken;
                _this.$axios.post(process.env.VUE_APP_SERVER + '/business/client/member/login',_this.member)
                    .then((responseClientLogin)=>{
                        let response=responseClientLogin.data;
                        if(response.success){
                            toast.success("登录成功！");
                            let memberLogin=response.responseData;
                            Tool.setLoginMember(response.responseData);
                            //判断remember me
                            if(_this.rememberme){
                                //保存密码密文，本地缓存
                                let new_md5=hex_md5(_this.member.password);
                                LocalStorage.set(MEMBER_LOGIN_LOCAL,memberLogin);
                            }else{
                                LocalStorage.set(MEMBER_LOGIN_LOCAL,null);
                            }
                            Tool.setLoginMember(memberLogin);// LOGIN_MEMBER
                            //TODO 登录成功之后，传给父组件<header>的member信息
                            _this.$parent.setMemberLogin(memberLogin);
                            $("#login-modal").modal('hide');

                        }else{
                            toast.warning("登录失败："+response.responseMsg);
                            _this.member.password="";
                            _this.loadImageCode();
                        }
                    })
            },
            /**
             * 发送短信验证码
             */
            sendMobileSMSCodeForRegister(){
                let _this=this;
                //增加Pattern验证拦截
                if(!_this.onRegisterMobileBlur()){
                    return false;
                }
                let shortMessage={
                    mobile: _this.memberRegister.mobile,
                    use:SHORT_MESSAGE_USE.REGISTER.key
                };
                //发送短信前进行后端手机号验证
                _this.$axios.get(process.env.VUE_APP_SERVER + '/business/client/shortMessage/mobileExist/'+_this.memberRegister.mobile)
                    .then((responseMobile)=>{
                        let response=responseMobile.data;
                        if(response.success){
                            toast.warning("该手机号已存在");
                        }else{
                            _this.sendMobileSMSCode(shortMessage,"register-send-code-btn");
                        }
                    });

            },
            //发送短信验证码请求
            sendMobileSMSCode(shortMessage,sendBtn){
                let _this=this;
                //调用短信发送接口
                _this.$axios.post(process.env.VUE_APP_SERVER + '/business/client/shortMessage/send',shortMessage)
                    .then((responseSM)=>{
                        let response=responseSM.data;
                        if(response.success){
                            toast.success("短信验证码发送成功");
                            //设置倒计时，按钮不可点击
                            _this.countDown=60;
                            _this.setSMTime(sendBtn);

                        }else{
                            toast.warning(response.responseMsg);
                        }
                    });
            },
            /**
             * 设置按钮倒计时
             */
            setSMTime(sendBtn){
                let _this=this;
                let btn=$("#"+sendBtn);
                if(_this.countDown===0){
                    btn.removeAttr("disabled");
                    btn.text("获取验证码");
                    //=0停止当前时间循环
                    return;
                }else{
                    //不为0，不可点击,显示倒计时
                    btn.attr("disabled",true);
                    btn.text("重新发送("+_this.countDown+")");
                    _this.countDown--;
                }
                //每1秒执行一次setTime
                setTimeout(function () {
                    _this.setSMTime(sendBtn);
                },1000);
            },
            //忘记密码发送验证码
            sendMobileSMSCodeForForget(){
                let _this=this;
                //增加Pattern验证拦截
                if(!_this.onForgetMobileBlur()){
                    return false;
                }
                let shortMessage={
                    mobile: _this.memberForget.mobile,
                    use:SHORT_MESSAGE_USE.FORGET.key
                };
                //发送短信前进行后端手机号验证
                _this.$axios.get(process.env.VUE_APP_SERVER + '/business/client/shortMessage/mobileExist/'+_this.memberForget.mobile)
                    .then((responseMobile)=>{
                        let response=responseMobile.data;
                        if(response.success){
                            _this.forgetMobileValidator=true;
                            _this.sendMobileSMSCode(shortMessage,"forget-send-code-btn");
                        }else{
                            _this.forgetMobileValidator=false;
                            toast.warning("手机号尚未注册");
                        }
                    });
            },
            /**
             * 忘记密码:/reset-password
             */
            resetPWD(){
                let _this=this;
                //[单注册校验]注册之前增加校验，一个文本框为false，都不提交return
                let validatorRules=_this.onForgetMobileBlur()
                    && _this.onForgetMobileCodeBlur()
                    && _this.onForgetPasswordBlur()
                    && _this.onForgetPasswordConfirmBlur();
                if(!validatorRules){
                    return ;
                }
                _this.memberForget.password=hex_md5(_this.memberForget.passwordOriginal+KEY);

                //调用更新密码接口
                _this.$axios.post(process.env.VUE_APP_SERVER + '/business/client/member/resetPWD',_this.memberForget)
                    .then((responseReset)=>{
                        let response=responseReset.data;
                        if(response.success){
                            toast.success("重置密码成功！");
                            _this.toLoginAcount();
                        }else{
                            toast.warning(response.responseMsg);
                        }
                    }).catch((responseErr)=>{
                })
            },
        }
    }
</script>

<style scoped>
    .modal-body{
        padding: 0
    }
    .form-content{
        padding: 30px;
    }
    /* 登录框 */
    .login-div .input-group-addon {
        padding: 0.5rem;
        border: 0;
    }
    /*header*/
    .loginHeader{
        background: #e92322;
        color: white;
        text-align: center;
        padding: 10px 0;
        border-top-right-radius: 5px;
        border-top-left-radius: 5px;
    }
    .loginHeader .dialogClose{
        color: white;
        opacity: 1;
        font-size: 26px;
        margin-top: -60px;
        margin-right: 10px;
        text-shadow:0 0px;
        font-weight:unset;
    }
    #login-modal h3 {
        padding: 0;
    }

    #login-modal .modal-login {
        max-width: 800px;
        margin: 130px auto;
    }
    /*取消样式，否则会隔行
    :not，如果id=idName则不响应当前样式
    */
    #login-modal input:not(.rememberme) {
        height: 45px;
        font-size: 16px;
    }

    #login-modal .submit-button {
        height: 50px;
        font-size: 20px;
    }

    #login-modal .to-login-acount {
        text-align: center;
    }
    /*输入验证码*/
    .loginInput{
        display: block;
        width: 100%;
        padding: 6px 12px;

        color: #555;
        background-color:#fff;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-shadow:inset 0 1px 1px rgba(0,0,0,.075);
        transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;
        height: 60px !important;
    }
    /*验证码*/
    .validateCode{
        float: left;
        width: 60%;
        margin-right: 10px;
    }
    .validateSendCode{

    }
    .clickButtom{
        background: #e92322;
        color: white;
        border:1px solid #b84545;
    }
    .clickButtom:hover,.clickButtom:focus{
        background: #f53433;
    }
    /*记住密码*/
    .checkbox input[type=checkbox]{
        position: relative;
        margin-right: 5px;
    }
    .checkBoxRemember{
        display: inline-block;

    }
</style>